﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Thor.SharePoint2007.WebServices
{
    public static class StringExtensions
    {
        public static DateTime? FromSharePointString(this string source)
        {
            var dateTimeSplit = source.Split(new char[] { ' ' });

            if (dateTimeSplit.Length == 2)
            {
                var date = dateTimeSplit[0];
                var time = dateTimeSplit[1];

                var dateSplit = date.Split(new char[] { '-' });

                if (dateSplit.Length != 3)
                    return null;

                int year;
                int month;
                int day;

                if(!int.TryParse(dateSplit[0], out year))
                    return null;

                if(!int.TryParse(dateSplit[1], out month))
                    return null;

                if (!int.TryParse(dateSplit[2], out day))
                    return null;

                var timeSplit = time.Split(new char[] { ':' });

                if (timeSplit.Length != 3)
                    return null;

                int hour;
                int minute;
                int second;

                if (!int.TryParse(timeSplit[0], out hour))
                    return null;

                if (!int.TryParse(timeSplit[1], out minute))
                    return null;

                if (!int.TryParse(timeSplit[2], out second))
                    return null;

                return new DateTime(year, month, day, hour, minute, second);
            }

            return null;
        }
    }
}
